package com.simple.util.http;

import com.simple.util.io.IOUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

/**
 * @program: simple_tools
 * @description: 文件下载工具类
 * @author: Mr.chen
 * @create: 2020-06-09 09:49
 **/
public class DownloadFileUtil {

    /**
     * 下载文件
     *
     * @param response
     * @param file
     * @param finishDeleteFile
     *            下载完成之后是否需要删除文件
     */
    public static void download(HttpServletResponse response, File file, boolean finishDeleteFile) {
        FileInputStream fis = null;
        ServletOutputStream out = null;
        try {
            // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("application/octet-stream");
            String downLoadName = new String(file.getName().getBytes("UTF-8"), "iso8859-1");
            // 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
            response.setHeader("Content-Disposition", "attachment;fileName=" + downLoadName);
            response.setHeader("Content-Length", String.valueOf(file.length()));
            fis = new FileInputStream(file);
            out = response.getOutputStream();
            int b = 0;
            byte[] buffer = new byte[1024];
            while ((b = fis.read(buffer)) != -1) {
                out.write(buffer, 0, b);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(out);
            IOUtil.close(fis);
            if (finishDeleteFile) {
                if ((file != null) && file.exists()) {
                    file.delete();
                }
            }
        }
    }

}
